
import java.io.*;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import java.util.List;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
import org.jdom.xpath.*;

import java.net.*;

@WebServlet(urlPatterns={"/commentserver/*"})
public class CommentServer extends HttpServlet {
   private static final long serialVersionUID = 1L;
   private static final String _dataFilePath = "/Users/hansii/Documents/workspace/web/webtek_js/WebContent/comments/comments.xml";
   public CommentServer() {
      super();
   }
   
   private Document loadXML(String xmlPath) throws JDOMException, IOException {
		File file = new File(xmlPath);
		Document doc;
		if (file.exists()) {
			doc = new SAXBuilder().build(file);
		} else {
			doc = new Document();
			Element root = new Element("images");
			doc.setRootElement(root);
		}
		return doc;
	}
   
   @SuppressWarnings("unchecked")	
   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
	   try {
           String uri = request.getRequestURI();
           uri = uri.substring(uri.indexOf("commentserver/")+14);
           Document doc = loadXML(_dataFilePath);
           XPath xp = XPath.newInstance("//images/image[@id = '"+URLDecoder.decode(uri, "UTF-8")+"']");
           List<Element> list = xp.selectNodes(doc);
           if (!list.isEmpty()) {
              XMLOutputter out = new XMLOutputter();
              out.output(list, response.getWriter());    
           }
           else
              response.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found"); // 404
           
       }
       catch (Exception ex) {
           response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal error occured: " + ex.getMessage()); // 500
       }
   }
   
   protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String uri = request.getRequestURI();
			uri = uri.substring(uri.indexOf("commentserver/")+14);
			BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
			String comment = br.readLine();
            Document doc = loadXML(_dataFilePath);
            Element commentElement = new Element("comment");
            commentElement.setText(comment);
 		    Element image = (Element)XPath.selectSingleNode(doc, "//images/image[@id = '"+URLDecoder.decode(uri, "UTF-8")+"']/comments");
 		    
 		    if (image == null) {
 		    	Element newImage = new Element("image");
 		    	newImage.setAttribute(new Attribute("id", uri));
 		    	Element comments = new Element("comments");
 		    	comments.addContent(commentElement);
 		    	newImage.addContent(comments);
 		    	Element images = (Element)XPath.selectSingleNode(doc, "//images");
 		    	images.addContent(newImage);	    	
 		    }
 		    else {
 		    	image.addContent(commentElement);
 		    }
            XMLOutputter xout = new XMLOutputter();
            java.io.FileWriter writer = new java.io.FileWriter(_dataFilePath);
            xout.output(doc, writer);
            writer.flush();
            writer.close();    
		} 
		catch (Exception e) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR , "Internal error occured: " + e.getMessage()); // 500
		}
	}
}
